from models.task import Task, STATUS_NOT_STARTED
from models.base import session
import threading

# 同步锁，多线程时有用
_lock = threading.Lock()


class TaskQueue:
    @staticmethod
    def get() -> Task or None:
        """
        获取任务
        :return: 成功获取返回Task，没有可执行任务时返回None
        """
        try:
            _lock.acquire()
            # 查询未开始状态的第一条任务
            task = session.query(Task).filter(Task.status == STATUS_NOT_STARTED).first()
            if not task:
                return None
            # 将任务状态改为 处理中
            task.process()
            return task
        finally:
            _lock.release()

    @staticmethod
    def put(task: Task) -> None:
        """
        添加新任务
        :param task:
        :return:
        """
        try:
            _lock.acquire()
            # 查询是否存在url相同的任务，如果没有，就新增任务
            task_first = session.query(Task).filter(Task.url == task.url).first()
            if not task_first:
                session.add(task)
                session.commit()
        finally:
            _lock.release()
